/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.biz.crawler.in;

import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.springframework.stereotype.Service;

import com.yunji.framework_template.biz.crawler.ContentImageHandler;
import com.yunji.framework_template.common.http.HttpClientUtil;
import com.yunji.framework_template.common.util.FileUtil;
import com.yunji.framework_template.common.util.ImageUtil;
import com.yunji.framework_template.common.util.StringUtil;
import com.yunji.framework_template.common.web.HttpResult;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassName:PunchngNewsImageHandler <br/>
 * Date: 2018年12月17日 下午5:22:00 <br/>
 * 
 * @author fenglibin1982@163.com
 * @Blog http://blog.csdn.net/fenglibing
 * @version
 * @see
 */
@Slf4j
@Service
public class IndiatodayNewsImageHandler extends ContentImageHandler {

    @Override
    public String getImage(String contentUrl) {
        try {
            HttpResult result = HttpClientUtil.doGet(contentUrl);
            if (result == null || result.getCode() != 200 || StringUtil.isEmpty(result.getContent())) {
                return null;
            }
            Element contentElement = new Element(Tag.valueOf("contents"), contentUrl);
            contentElement.html(result.getContent());
            Element element = contentElement.select("div[itemprop=\"associatedMedia image\"]").first();
            Element element2 = contentElement.select("div[itemprop=\"image\"]").first();
            if (element != null) {
                return ImageUtil.getImageFromImageElement(ImageUtil.getOneImgFromImageElements(element.select("img")));
            }else if (element2 != null) {
                return ImageUtil.getImageFromImageElement(ImageUtil.getOneImgFromImageElements(element2.select("img")));
            }
            FileUtil.writeFile("/tmp/1.html", result.getContent());
            String image = StringUtil.subString(result.getContent(), "image: \"", "\",");
            if(image==null) {
                image = StringUtil.subString(result.getContent(), "image: '", "',");
            }
            return image;
            
        } catch (Exception e) {
            log.error("Get image from url " + contentUrl + " exception happened:" + e.getMessage(), e);
        }
        return null;
    }

}
